import React, { PureComponent } from "react";
import { Card, Table, Switch, Modal} from "antd";
import { connect } from "dva";
import dynamic from "umi/dynamic";
import styles from "./index.less";

import CardTitle from "./components/CardTitle";

import {
  getMenuRouter,
  getPageOperate,
} from "../../../components/layouts/menuFn";

import { openNotificationWithIcon, delay } from "../../../utils/comm";
 // Tooltip
const { confirm } = Modal;

const AdvancedFilter = dynamic({ loader: async () => {
  // await delay(1000);
  return import("./components/AdvancedFilter");
} });
const EntrustDetail = dynamic({ loader: async () => {
  await delay(1000);
  return import("./components/EntrustDetail");
},
});


@connect(({ Entrust, loading }) => ({
  entrustStore: Entrust,
  loading,
}))
class Entrust extends PureComponent {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.getMenuRouter = getMenuRouter.bind(this);
    this.getPageOperate = getPageOperate.bind(this);
    this.state = {
      page: {
        pageNum: 1,
        pageSize: 6,
      },
      entrustVisible: false,
      entrustDetailLoaded: false,
      entrustDetailTitle: '',
      entrustDetailData: {

      },
      currentStep: 0,
      // eslint-disable-next-line react/no-unused-state
      entrustDataListCheckedRows: [],
      // eslint-disable-next-line react/no-unused-state
      entrustDataListCheckedKeys: [],
    };
    this.baseQueryParam = {
      entrustName: '',
      trustee: '', // 受托人
      status: -1,
      startUpdateTime: '',
      endUpdataTime: '',
      flowName: '',
    };
    this.queryParams = this.baseQueryParam;
    this.columns = [
      {
        title: "委托编码",
        align: 'center',
        dataIndex: "code",
      },
      {
        title: "委托名称",
        align: 'center',
        dataIndex: "entrustName",
      },
      {
        title: "委托人",
        align: 'center',
        dataIndex: "client",
      },
      {
        title: "受托人",
        align: 'center',
        dataIndex: "trustee",
      },
      {
        title: "委托类型",
        align: 'center',
        dataIndex: "isDefault",
        render: (text) => {
          return (
            <span>
              { text === 0 ? '自定义委托' : '默认委托'}
            </span>
          )
        },
      },
      {
        title: "状态",
        align: 'center',
        dataIndex: "status",
        render: (text, record, index) => {
          return (
            <Switch
              // defaultChecked={text!==0}
              checked={text!==0}
              onChange={(val) => {
                if(val) {
                  record.status = 1;
                } else {
                  record.status = 0;
                }
                const { dispatch } = this.props;
                const {id, isDefault, status} = record;
                dispatch({
                  type: "Entrust/updateEntrustStatusById",
                  payload: { id, isDefault, status },
                }).then((res) => {
                  const { entrustStore } = this.props;
                  const { entrustListData = [] } = entrustStore;
                  if (res.errCode === 0) {
                    this.openNotificationWithIcon("success", "", "委托状态更新成功");
                    if(val) {
                      entrustListData.forEach((element, inde) => {
                        if(element === record) {
                          entrustListData[inde].status = 1;
                        }
                        (element.flowEntrustDetailVoList ? element.flowEntrustDetailVoList : []).forEach((item, ind) => {
                          if(item === record) {
                            entrustListData[inde].flowEntrustDetailVoList[ind].status = 1;
                          }
                        })
                      });
                    } else {
                      entrustListData.forEach((element, inde) => {
                        if(element === record) {
                          entrustListData[inde].status = 0;
                          (element.flowEntrustDetailVoList ? element.flowEntrustDetailVoList : []).forEach((item, ind) => {
                            entrustListData[inde].flowEntrustDetailVoList[ind].status = 0;
                          })
                        }
                        (element.flowEntrustDetailVoList ? element.flowEntrustDetailVoList : []).forEach((item, ind) => {
                          if(item === record) {
                            entrustListData[inde].flowEntrustDetailVoList[ind].status = 0;
                          }
                        })
                      });
                    }
                  } else {
                    this.openNotificationWithIcon("error", "", res.errMsg || "更新失败");
                    if(val) {
                      entrustListData.forEach((element, inde) => {
                        if(element === record) {
                          entrustListData[inde].status = 0;
                        }
                        (element.flowEntrustDetailVoList ? element.flowEntrustDetailVoList : []).forEach((item, ind) => {
                          if(item === record) {
                            entrustListData[inde].flowEntrustDetailVoList[ind].status = 0;
                          }
                        })
                      });
                    } else {
                      entrustListData.forEach((element, inde) => {
                        if(element === record) {
                          entrustListData[inde].status = 1;
                          (element.flowEntrustDetailVoList ? element.flowEntrustDetailVoList : []).forEach((item, ind) => {
                            entrustListData[inde].flowEntrustDetailVoList[ind].status = 1;
                          })
                        }
                        (element.flowEntrustDetailVoList ? element.flowEntrustDetailVoList : []).forEach((item, ind) => {
                          if(item === record) {
                            entrustListData[inde].flowEntrustDetailVoList[ind].status = 1;
                          }
                        })
                      });
                    }
                  }
                  dispatch({
                    type: "Entrust/go",
                    payload: entrustListData,
                  });
                });
              }}
              checkedChildren="开"
              unCheckedChildren="关"
            />
          )
        },
      },
      {
        title: "更新时间",
        align: 'center',
        dataIndex: "updateTime",
      },
      {
        title: "操作",
        align: 'center',
        render: (text, record) => {
          return (
            <div>
              {record.isDefault === 1 && (
              <span
                style={{color:'#1890FF', cursor: 'pointer'}}
                onClick={() => {
                const { dispatch } = this.props;
                const {id, isDefault, entrustId} = record;
                let idData = '';
                if(isDefault === 0) {
                  idData = entrustId
                } else {
                  idData = id
                }
                dispatch({
                  type: "Entrust/getEntrustData",
                  payload: { id: idData },
                }).then((res) => {
                  if (res.payload.id) {
                    this.setState({entrustDetailData: res.payload})
                    this.setState({
                      entrustVisible: true,
                      entrustDetailTitle: '修改委托',
                    })
                    this.setState({ currentStep: 1 });
                    // if(isDefault === 0) {
                    //   // 自定义委托
                    //   this.setState({ currentStep: 1 });
                    // } else {
                    //   this.setState({ currentStep: 0 });
                    // }
                  } else {
                    this.openNotificationWithIcon("error", "", res.errMsg || "获取数据失败");
                  }
                });
              }}
              >
                修改
              </span>
            )}
              <span
                style={{paddingLeft:'5px',color:'#1890FF', cursor: 'pointer'}}
                onClick={() => {
                  const handle = this.handleDel;
                  confirm({
                    title: '确定删除这一项吗?',
                    okText:'确定',
                    cancelText: '取消',
                    onOk() {
                      handle(record)
                    },
                    onCancel() {},
                  });
                }}
              >
                删除
              </span>
              <span
                style={{paddingLeft:'5px',color:'#1890FF', cursor: 'pointer'}}
                onClick={() => {
                  const { dispatch } = this.props;
                  const {clientCode, trusteeCode, modelKey} = record;

                  dispatch({
                    type: "Entrust/entrustTaskData",
                    payload: { client: clientCode, entrustToUserCode: trusteeCode, modelKey: modelKey || '' },
                  }).then((res) => {
                    if (res.errCode === 0) {
                      this.openNotificationWithIcon("success", "", "待办委派成功");
                      this.initData();
                    } else {
                      this.openNotificationWithIcon("error", "", res.errMsg || "失败");
                    }
                    });
                }}
              >
                待办委派
              </span>
            </div>
          )
        },
      },
    ];
    this.rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        // eslint-disable-next-line react/no-unused-state
        this.setState({customedEntrustDataListCheckedRows: selectedRows, customedEntrustDataListCheckedKeys: selectedRowKeys})
      },
    };
  }

  componentDidMount() {
    this.initData();
  }

  // 获取查询条件组件的this
  getRef = (type, _this) => {
    this[type] = _this;
  };

  // 获取查询参数
  getQueryParam = () => {
    const {
      page: { pageNum, pageSize },
    } = this.state;
    return { ...this.queryParams, pageNum, pageSize };
  };

  // 查询条件改变
  handleParamsChange = (item = {}) => {
    this.queryParams = { ...this.queryParams, ...item };
  };

  // 触发查询
  initData = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParam();
    dispatch({ type: "Entrust/getEntrustListData", payload: params });
  };

  handlePageChange = ({ current: pageNum, pageSize }) => {
    this.setState({ page: { pageNum, pageSize } }, () => {
      this.initData();
    });
  };

  // 搜索
  handleSearch = () => {
    const { page } = this.state;
    this.setState({ page: { ...page, pageNum: 1 } }, () => {
      this.initData();
    });
  };

  // 删除
  handleDel = (record = {}) => {
    const { dispatch } = this.props;
    const { id, isDefault } = record;
    if (!id) return;
    dispatch({
      type: "Entrust/deleteEntrust",
      payload: { id, isDefault },
    }).then((res) => {
      if (res.errCode === 0) {
        this.openNotificationWithIcon("success", "", "删除成功");
        this.initData();
      } else {
        this.openNotificationWithIcon("error", "", res.errMsg || "删除失败");
      }
    });
  };


  handleAdd = () => {
    const { entrustVisible } = this.state;
    this.setState({ currentStep: 0, entrustVisible: !entrustVisible, entrustDetailLoaded: false, entrustDetailData: {}, entrustDetailTitle:'新建委托' });
  }

  handleDelete = () => {

  }

  handleEntrustDetailVisible = (entrustVisible) => {
    this.setState({ entrustVisible });
    this.setState({ currentStep: 0 });
    this.initData();
  }

  handleEntrustDetailData = (values, submit) => {
    const { dispatch } = this.props;
    this.setState((state) => {
      return {entrustDetailData: {...state.entrustDetailData, ...values}}
    },() => {
        const {entrustDetailData} = this.state
        if(submit) {
          dispatch({ type: "Entrust/addEntrustData", payload: entrustDetailData }).then((res) => {
            if (res.errCode === 0) {
              this.openNotificationWithIcon("success", "", "保存成功");
              this.setState({entrustVisible: false})
              this.initData();
            } else {
              this.openNotificationWithIcon("error", "", res.errortext);
            }
          })
        }
    });

  }

  handleCurrentStep = (val) => {
    this.setState({currentStep: val});
  }

  render() {
    const { entrustStore, loading } = this.props;
    const {
      page: { pageNum, pageSize },
      entrustVisible,
      entrustDetailLoaded,
      entrustDetailData,
      entrustDetailTitle,
      currentStep,
    } = this.state;
    const { entrustListData = [], totalCount = 0 } = entrustStore;
    const listLoading =
      loading.effects["Entrust/getEntrustList"] || false;

    return (
      <div className={styles.root}>
        <AdvancedFilter
          visible
          getRef={(_this) => this.getRef("AdvancedFilter", _this)}
          handleSearch={this.handleSearch}
          handleParamsChange={this.handleParamsChange}
        />
        <Card
          title={
            <CardTitle
              handleAdd={this.handleAdd}
              handleDelete={this.handleDelete}
              total={totalCount}
            />
                }
          bodyStyle={{
                  minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104,
                }}
          style={{ width: "100%" }}
        >
          <Table
            dataSource={entrustListData}
            loading={listLoading}
            columns={this.columns}
            scroll={{x: 1200}}
            rowKey="$id"
            bordered
            className={styles.spacing}
            onChange={this.handlePageChange}
            rowSelection={this.rowSelection}
            childrenColumnName="flowEntrustDetailVoList"
            pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: ["6", "10", "20", "30"],
                    current: pageNum,
                    pageSize,
                    total: totalCount,
                  }}
          />
        </Card>
        <EntrustDetail
          visible={entrustVisible}
          entrustDetailLoaded={entrustDetailLoaded}
          entrustDetailTitle={entrustDetailTitle}
          entrustDetailData={entrustDetailData}
          currentStep={currentStep}
          handleCurrentStep={this.handleCurrentStep}
          handleEntrustDetailVisible={this.handleEntrustDetailVisible}
          handleEntrustDetailData={this.handleEntrustDetailData}
        />
      </div>
    );
  }
}

export default Entrust;
